import requests
import os
import time

if os.path.exists("oiapi"):
    with open("oiapi", "r") as file:
        oiapi = file.read().strip()
else:
    oiapi = input("输入你的OIAPI:")
    with open("oiapi", "w") as file:
        file.write(oiapi)
    print("已保存至oiapi内")


def get_chapter_number(book_id):
    params = {
        "id": book_id,
        "key": oiapi
    }
    response = requests.get("https://oiapi.net/api/FqRead", params=params)
    if response.status_code == 200:
        data = response.json()
        chapter_number = data["data"]["serial"]
        bookname = data["data"]["title"]
        return bookname, chapter_number
    else:
        return None

def download_book_by_id(book_id, start_chapter, end_chapter):
    chapters = range(start_chapter, end_chapter)
    result = ','.join(str(num) for num in chapters)
    params = {
        "id": book_id,
        "key": oiapi,
        "chapter": result
    }
    request = requests.get("https://oiapi.net/api/FqRead", params=params)
    if request.status_code == 200:
        data = request.json()
        return data

def download(bookid, minstep):
    bookname, chapter_number = get_chapter_number(bookid)
    i = 1
    filepath = f"data/{bookname}.txt"
    if os.path.exists(filepath):
        os.remove(filepath)
    while i <= chapter_number:
        min = i + minstep
        if min > chapter_number:
            min = chapter_number + 1
        data = download_book_by_id(bookid, i, min)
        chapters = data["data"]
        extracted = []
        print(f"正在下载第{i}章到第{min}章")
        for temp in range(len(range(i, min))):
            item = chapters[temp]
            chapter = item['chapter']
            content = item['content']
            # 确保只保留需要的字段
            chapter_info = {
            'chapter': chapter,
            'content': content
            }
            extracted.append(chapter_info)
        sorted_chapters = sorted(extracted, key=lambda x: int(x['chapter']) if x['chapter'] else 0)
        with open(f"data/{bookname}.txt", "a", encoding="utf-8") as file:
            for single in sorted_chapters:
                file.write(f"{single['content']}\n\n")
        i = i + minstep
        time.sleep(0.5)
    return os.path.abspath(f"data/{bookname}.txt")
if __name__ == "__main__":
    bookid = input("输入bookid:")
    download(bookid, 50)